﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Opds_Viewer.Utils;

namespace Opds_Viewer.Model
{
    /// <summary>
    /// Class describing a list of MyCatalog
    /// </summary>
    public class MyCatalogs : List<MyCatalog>
    {
        #region properties

        private static MyCatalogs _sInstance;
        private static readonly object SInstanceLocker = new object();

        #endregion

        #region constructor

        /// <summary>
        /// Initializes a new instance of the <see cref="MyCatalogs"/> class.
        /// </summary>
        public MyCatalogs()
        {
            this.GetAllCatalogs();
        }

        #endregion

        /// <summary>
        /// Gets the instance.
        /// </summary>
        /// <value>The instance.</value>
        public static MyCatalogs Instance
        {
            get
            {
                lock (SInstanceLocker)
                {
                    return _sInstance ?? (_sInstance = new MyCatalogs());
                }
            }
        }

        /// <summary>
        /// Load all the catalogs in the config file
        /// </summary>
        public void GetAllCatalogs()
        {
            var doc = XDocument.Load(Properties.Settings.Default.XmlCatalogs);
            var root = doc.Element(XmlCatNode.Root);

            // Error in the xml file
            if (root == null) return;

            foreach (var myCat in root.Elements(XmlCatNode.Catalog).Select(cat => new MyCatalog(cat)))
            {
                this.Add(myCat);
            }
        }

        /*public Dictionary<string,DateTime> GetUpdates()
        {
            var dict = new Dictionary<string, DateTime>();

            var doc = XDocument.Load("Catalogs/MyCatalogs.xml");
            var root = doc.Element("catalogs");
            if (root != null)
                foreach (var cat in root.Elements("catalog"))
                {
                    var url = cat.Element("url");
                    if (url == null || string.IsNullOrEmpty(url.Value)) continue;

                    var dt = cat.Element("lastupdate");
                    var date = DateTime.MinValue;
                    if (dt != null && !string.IsNullOrEmpty(dt.Value))
                    {
                        date = DateTime.Parse(dt.Value);
                    }

                    dict.Add(url.Value,date);
                }

            return dict;
        }*/
    }
}